import socket

import os


class Server:
    def __init__(self):
        self.ss=socket.socket()
        self.bind=('0.0.0.0',8888)
        self.save_dir='data/'


    def start(self):
        self.ss.bind(self.bind)
        self.ss.listen()
        conn,addr=self.ss.accept()
        self.receive_file(conn,addr)

    def receive_file(self,conn,addr):

        print('{}已经建立连接：'.format(addr[0]))
        forward_msg=conn.recv(1024)
        forward_msg_de=forward_msg.decode()
        cmd,filename,filesize=forward_msg_de.split('|')
        size=int(filesize)
        path=os.path.join(self.save_dir,filename)
        self.save_msg(size,path,conn)

    def save_msg(self,size,path,conn):
        has_recv=0
        while has_recv != size:
            with open(path,'wb') as f:
                data=conn.recv(1024)
                f.write(data)
                has_recv +=len(data)
                print('已经收到{:.2}'.format(has_recv/size))
        print('完成传输！')


if __name__ == '__main__':
    s=Server()
    s.start()



